<template>
  <el-drawer
    v-model="drawerData.show"
    :size="drawerData.size"
    :title="title"
    :transfer="false"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <BasicVxeForm v-model:collapseStatus="collapseStatus" ref="formRef" :formOptions="formOptions">
      <template #collapseNode>
        <div style="display: flex; justify-content: space-between">
          <span style="font-size: 16px; font-weight: bold">员工其他信息：</span>
          <el-button type="primary" link @click="collapseStatus = !collapseStatus">
            <template v-if="collapseStatus">
              {{ $t('system.展开') }}
              <i class="iconfont-sys iconsys-xia2"></i>
            </template>
            <template v-else>
              {{ $t('system.收起') }}
              <i class="iconfont-sys iconsys-shang2"></i>
            </template>
          </el-button>
        </div>
      </template>
    </BasicVxeForm>

    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleCancel">{{ $t('system.取消') }}</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">{{
          $t('system.提交')
        }}</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
  import { ElMessage } from 'element-plus'
  import { CreateUser, UpdateUser } from '@/api/persondocument'

  interface FormV0 {
    employeeCode: string
    firstName: string
    jobTitleId: string
    gender: string
    nationId: string
    state: string
  }

  interface OpenCallBackParams {
    type: 'add' | 'edit'
    row?: Recordable
  }

  const props = defineProps<{
    gongZhongList: LabelValueOption[]
  }>()

  const emits = defineEmits(['success'])

  const drawerData = reactive({
    show: false,
    size: 500
  })

  const reactData = ref<OpenCallBackParams>({} as OpenCallBackParams)
  const submitting = ref(false)
  const collapseStatus = ref(true)

  const isUpdate = computed(() => reactData.value.type === 'edit')
  const title = computed(() => (!isUpdate.value ? '添加员工' : '编辑员工'))

  const openDrawer = (show = true, data?: OpenCallBackParams) => {
    drawerData.show = show
    if (data) {
      // 等待渲染完成
      nextTick(() => {
        handleOpenCallback(data)
      })
    }
  }

  const closeDrawer = () => {
    drawerData.show = false
  }

  const handleOpenCallback = (data: OpenCallBackParams) => {
    // 每次打开重置表单
    formRef.value?.reset()

    reactData.value = data

    if (isUpdate.value) {
      formOptions.data = data.row
    }
  }

  const handleCancel = () => {
    closeDrawer()
  }

  const handleSubmit = async () => {
    try {
      const errMaps = await formRef.value?.validate()

      // 沒有错误才是校验成功
      if (!errMaps) {
        submitting.value = true
        const submitData = formRef.value?.getFormData()

        if (!isUpdate.value) {
          await CreateUser(submitData)
        } else {
          await UpdateUser(reactData.value.row?.id, submitData)
        }

        closeDrawer()
        emits('success')
      } else {
        ElMessage.error('请把必填项补全，检查无误后在提交')
      }
    } catch (err) {
      console.error(err)
    } finally {
      submitting.value = false
    }
  }

  const parasSetting = {
    genderList: [
      {
        value: '男',
        label: '男'
      },
      {
        value: '女',
        label: '女'
      }
    ],
    stateList: [
      {
        value: '在职',
        label: '在职'
      },
      {
        value: '离职',
        label: '离职'
      }
    ],
    nationList: [
      {
        value: '汉族',
        label: '汉族'
      },
      {
        value: '满族',
        label: '满族'
      },
      {
        value: '蒙古族',
        label: '蒙古族'
      },
      {
        value: '回族',
        label: '回族'
      },
      {
        value: '藏族',
        label: '藏族'
      },
      {
        value: '维吾尔族',
        label: '维吾尔族'
      },
      {
        value: '苗族',
        label: '苗族'
      },
      {
        value: '彝族',
        label: '彝族'
      },
      {
        value: '壮族',
        label: '壮族'
      },
      {
        value: '布依族',
        label: '布依族'
      },
      {
        value: '侗族',
        label: '侗族'
      },
      {
        value: '瑶族',
        label: '瑶族'
      },
      {
        value: '白族',
        label: '白族'
      },
      {
        value: '土家族',
        label: '土家族'
      },
      {
        value: '哈尼族',
        label: '哈尼族'
      },
      {
        value: '哈萨克族',
        label: '哈萨克族'
      },
      {
        value: '傣族',
        label: '傣族'
      },
      {
        value: '黎族',
        label: '黎族'
      },
      {
        value: '其他',
        label: '其他'
      }
    ],
    titleList: [
      {
        value: '初级',
        label: '初级'
      },
      {
        value: '中级',
        label: '中级'
      },
      {
        value: '高级',
        label: '高级'
      },
      {
        value: '其他',
        label: '其他'
      }
    ],
    educationList: [
      {
        value: '小学',
        label: '小学'
      },
      {
        value: '中学',
        label: '中学'
      },
      {
        value: '高中',
        label: '高中'
      },
      {
        value: '中专',
        label: '中专'
      },
      {
        value: '大专',
        label: '大专'
      },
      {
        value: '本科',
        label: '本科'
      },
      {
        value: '研究生',
        label: '研究生'
      },
      {
        value: '其他',
        label: '其他'
      }
    ],
    oldAgeInsuranceList: [
      {
        value: '参加',
        label: '参加'
      },
      {
        value: '未参加',
        label: '未参加'
      }
    ]
  }

  const formRef = ref<BasicFormInstance>()
  const formOptions = reactive<BasicFormProps<FormV0>>({
    data: {},
    rules: {
      employeeCode: [{ required: true, content: '员工号不能为空' }],
      firstName: [{ required: true, content: '员工姓名不能为空' }],
      jobTitleId: [{ required: true, content: '工种不能为空' }]
    },
    items: [
      {
        field: 'employeeCode',
        title: '员工号',
        span: 24,
        itemRender: { name: 'ElInput' }
      },
      {
        field: 'firstName',
        title: '员工姓名',
        span: 24,
        itemRender: { name: 'ElInput' }
      },
      {
        field: 'jobTitleId',
        title: '工种',
        span: 24,
        itemRender: {
          name: 'ElSelect',
          options: computed(() => props.gongZhongList) as unknown as LabelValueOption[]
        }
      },
      {
        field: 'gender',
        title: '性别',
        span: 24,
        itemRender: {
          name: 'ElSelect',
          options: parasSetting.genderList
        }
      },
      {
        field: 'nationId',
        title: '身份证号',
        span: 24,
        itemRender: { name: 'ElInput' }
      },
      {
        field: 'phoneId',
        title: '手机号',
        span: 24,
        itemRender: { name: 'ElInput' }
      },
      {
        field: 'email',
        title: '邮箱',
        span: 24,
        itemRender: { name: 'ElInput' }
      },
      {
        field: 'state',
        title: '状态',
        span: 24,
        itemRender: {
          name: 'ElSelect',
          options: parasSetting.stateList
        }
      },
      {
        span: 24,
        slots: {
          default: 'collapseNode'
        }
      },
      {
        field: 'birthDay',
        title: '出生年月',
        span: 12,
        folding: true,
        itemRender: {
          name: 'ElDatePicker',
          props: { format: 'YYYY-MM-DD', valueFormat: 'YYYY-MM-DD' }
        }
      },
      {
        field: 'nation',
        title: '民族',
        span: 12,
        folding: true,
        itemRender: {
          name: 'ElSelect',
          options: parasSetting.nationList
        }
      },
      {
        field: 'oldAgeInsurance',
        title: '养老保险',
        span: 12,
        folding: true,
        itemRender: {
          name: 'ElSelect',
          options: parasSetting.oldAgeInsuranceList
        }
      },
      {
        field: 'hireDate',
        title: '入职时间',
        span: 12,
        folding: true,
        itemRender: {
          name: 'ElDatePicker',
          props: { format: 'YYYY-MM-DD', valueFormat: 'YYYY-MM-DD' }
        }
      },
      {
        field: 'dimissionDate',
        title: '离职时间',
        span: 12,
        folding: true,
        // 编辑才有离职时间
        visibleMethod: () => reactData.value.type === 'edit',
        itemRender: {
          name: 'ElDatePicker',
          props: { format: 'YYYY-MM-DD', valueFormat: 'YYYY-MM-DD' }
        }
      },
      {
        field: 'title',
        title: '职称',
        span: 12,
        folding: true,
        itemRender: {
          name: 'ElSelect',
          options: parasSetting.titleList
        }
      },
      {
        field: 'education',
        title: '学历',
        span: 12,
        folding: true,
        itemRender: {
          name: 'ElSelect',
          options: parasSetting.educationList
        }
      },
      {
        field: 'address',
        title: '家庭地址',
        span: 24,
        folding: true,
        itemRender: { name: 'ElInput' }
      }
    ]
  })

  defineExpose({
    openDrawer,
    closeDrawer
  })
</script>
